package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/ravener/discord-oauth2"
	"golang.org/x/oauth2"
	"io/ioutil"
	"log"
	"net/http"
	"net/url"
	"strings"
	_ "time"
)

func main() {
	//var state = "rand"
	var Endpoint = oauth2.Endpoint{
		AuthURL:   "https://discordapp.com/api/v9/oauth2/authorize",
		TokenURL:  "https://discordapp.com/api/oauth2/token",
		AuthStyle: oauth2.AuthStyleInParams,
	}
	conf := &oauth2.Config{
		RedirectURL: "http://127.0.0.1:3000/auth/callback",
		// This next 2 lines must be edited before running this.
		ClientID:     "1044168747751055430",
		ClientSecret: "dzktUD4HPpUqt6lemV4BQvwEcDthMEmy",
		Scopes:       []string{discord.ScopeIdentify},
		Endpoint:     Endpoint,
	}

	g := gin.Default()
	//g.Use(LoggerToFile())
	// Step 1: Redirect to the OAuth 2.0 Authorization page.
	// This route could be named /login etc
	g.POST("/discord-login", func(ctx *gin.Context) {
		body, _ := ioutil.ReadAll(ctx.Request.Body)
		fmt.Println(ctx.Request.Body)
		fmt.Println(ctx.Request.Header)
		fmt.Println(string(body))
		//ctx.Redirect(http.StatusTemporaryRedirect, conf.AuthCodeURL(state))
		ctx.JSON(200,gin.H{
			"status":"ok",
		})
		//http.Redirect(ctx.Writer, ctx.Request, conf.AuthCodeURL(state), http.StatusTemporaryRedirect)
	})
	// Step 2: After user authenticates their accounts this callback is fired.
	// the state we sent in login is also sent back to us here
	// we have to verify it as necessary before continuing.
	g.GET("/auth/callback", func(ctx *gin.Context) {
		//value, _ := ctx.GetQuery("state")
		//if value != state {
		//	ctx.Writer.WriteHeader(http.StatusBadRequest)
		//	ctx.Writer.Write([]byte("State does not match."))
		//	return
		//}
		// Step 3: We exchange the code we got for an access token
		// Then we can use the access token to do actions, limited to scopes we requested
		code, _ := ctx.GetQuery("code")
		client := &http.Client{}
		postData := url.Values{}
		postData.Add("client_id", conf.ClientID)
		postData.Add("client_secret", conf.ClientSecret)
		postData.Add("grant_type", "authorization_code")
		postData.Add("code", code)
		postData.Add("redirect_uri",conf.RedirectURL)

		req,err := http.NewRequest("POST",conf.Endpoint.TokenURL,strings.NewReader(postData.Encode()))
		if err != nil{
			return
		}
		//伪装头部
		req.Header.Add("Content-Type","application/x-www-form-urlencoded")
		//提交请求
		resp,err := client.Do(req)
		defer resp.Body.Close()
		if err != nil{
			return
		}
		//读取返回值
		result,err := ioutil.ReadAll(resp.Body)
		if err != nil{
			return
		}
		//token, err := conf.Exchange(ctx, code)
		if err != nil {
			ctx.Writer.WriteHeader(http.StatusInternalServerError)
			ctx.Writer.Write([]byte(err.Error()))
			return
		}
		fmt.Println(result)
		// Step 4: Use the access token, here we use it to get the logged in user's info.
		res, err := conf.Client(ctx, token).Get("https://discord.com/api/users/@me")

		if err != nil || res.StatusCode != 200 {

			ctx.Writer.WriteHeader(http.StatusInternalServerError)
			if err != nil {
				ctx.Writer.Write([]byte(err.Error()))
			} else {
				ctx.Writer.Write([]byte(res.Status))
			}
			return
		}
		//
		//defer res.Body.Close()
		//
		//body, err := ioutil.ReadAll(res.Body)
		//
		//if err != nil {
		//	ctx.Writer.WriteHeader(http.StatusInternalServerError)
		//	ctx.Writer.Write([]byte(err.Error()))
		//	return
		//}
		//ctx.Writer.Write()
	})
	_ = g.Run(":3000")
	log.Println("alertmanager webhook start success!!!!")
}

//func LoggerToFile() gin.HandlerFunc {
//	logger := Logger()
//	return func(c *gin.Context) {
//		// 开始时间
//		startTime := time.Now()
//
//		// 处理请求
//		c.Next()
//
//		// 结束时间
//		endTime := time.Now()
//
//		// 执行时间
//		latencyTime := endTime.Sub(startTime)
//
//		// 请求方式
//		reqMethod := c.Request.Method
//
//		// 请求路由
//		reqUri := c.Request.RequestURI
//
//		// 状态码
//		statusCode := c.Writer.Status()
//
//		// 请求IP
//		clientIP := c.ClientIP()
//
//		//日志格式
//		logger.Infof("| %3d | %13v | %15s | %s | %s |",
//			statusCode,
//			latencyTime,
//			clientIP,
//			reqMethod,
//			reqUri,
//		)
//	}
//}

//func Logger() *logrus.Logger {
//	now := time.Now()
//	logFilePath := ""
//	if dir, err := os.Getwd(); err == nil {
//		logFilePath = dir + "/logs/"
//	}
//	if err := os.MkdirAll(logFilePath, 0777); err != nil {
//		log.Println(err.Error())
//	}
//	logFileName := now.Format("2006-01-02") + ".log"
//	//日志文件
//	fileName := path.Join(logFilePath, logFileName)
//	if _, err := os.Stat(fileName); err != nil {
//		if _, err := os.Create(fileName); err != nil {
//			log.Println(err.Error())
//		}
//	}
//	//写入文件
//	src, err := os.OpenFile(fileName, os.O_APPEND|os.O_WRONLY, os.ModeAppend)
//	if err != nil {
//		log.Println("err", err)
//	}
//
//	//实例化
//	logger := logrus.New()
//
//	//设置输出
//	logger.Out = src
//
//	//设置日志级别
//	logger.SetLevel(logrus.DebugLevel)
//
//	//设置日志格式
//	logger.SetFormatter(&logrus.TextFormatter{
//		TimestampFormat: "2006-01-02 15:04:05",
//	})
//	return logger
//}
